package com.coolweather.android;

import static com.coolweather.android.constants.Constants.PROVINCE_URL;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Toast;

import androidx.fragment.app.Fragment;

import com.coolweather.android.databinding.ChooseAreaBinding;
import com.coolweather.android.db.City;
import com.coolweather.android.db.County;
import com.coolweather.android.db.Province;
import com.coolweather.android.util.HttpUtil;
import com.coolweather.android.util.Utility;

import org.jetbrains.annotations.NotNull;
import org.litepal.LitePal;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class ChooseAreaFragment extends Fragment {
    public static final String PROVINCE = "province";
    public static final String CITY = "city";
    public static final String COUNTY = "county";
    ChooseAreaBinding binding;

    public static final int LEVEL_PROVINCE = 0;//省级
    public static final int LEVEL_CITY = 1;//市级
    public static final int LEVEL_COUNTY = 2;//县级  ctrl+alt+L 格式化代码
    private int currentLevel = LEVEL_PROVINCE;//当前显示的省级列表  currentLevel=0;

    List<Province> provinceList;//省的集合数据
    List<City> cityList;//市的集合数据
    List<County> countyList;//县的集合

    private Province selectedProvince;//选中的省份信息
    private City selectedCity;//选中的市份信息

    List<String> dataList = new ArrayList<>();//存放省份名称列表、市名称列表、县名称列表 与列表适配器 配合使用
    ArrayAdapter<String> adapter;

    ProgressDialog progressDialog;//加载进度对话框

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = ChooseAreaBinding.inflate(inflater, container, false);

        //适栩器的初始化
        adapter=new ArrayAdapter<>(getActivity(),android.R.layout.simple_list_item_1,dataList);


        //为列表组件设置适配器
        binding.listView.setAdapter(adapter);


        return binding.getRoot();
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        //绑定列表项的点击事件
        binding.listView.setOnItemClickListener((adapterView, view, position, id) -> {
            if(currentLevel==LEVEL_PROVINCE){
                selectedProvince=provinceList.get(position);//获取选中项（某个省份）
                queryCities();//查询城市
            }else if(currentLevel==LEVEL_CITY){
                selectedCity=cityList.get(position);//获取选中项（某个省份）
                queryCounties();//查询城市
            }else if(currentLevel==LEVEL_COUNTY){
                //把当前的位置还有weatherId传过去  CNXXXX  --->XXXX
                County county = countyList.get(position);
                String spot=String.format("%s|%s|%s",
                selectedProvince.getProvinceName(),
                        selectedCity.getCityName(),
                        county.getCountyName());
                String location= county.getWeatherId().substring(2);
                Log.d("test", "onActivityCreated: "+spot+"|"+location);

                Intent intent=new Intent(getActivity(),WeatherActivity.class);
                intent.putExtra("spot",spot);
                intent.putExtra("location",location);
                startActivity(intent);
                getActivity().finish();



            }
        });

        binding.backButton.setOnClickListener(v->{
            if(currentLevel==LEVEL_CITY){
                queryProvinces();
            }else if(currentLevel==LEVEL_COUNTY){
                queryCities();
            }
        });

        queryProvinces();//查询省份

    }

    private void queryCounties() {
        binding.titleText.setText(selectedProvince.getProvinceName()+":"+selectedCity.getCityName());
        binding.backButton.setVisibility(View.VISIBLE);//有返回按钮，可以返回到省一级

        //访问数据库表
        countyList = LitePal.where("cityId=?",
                String.valueOf(selectedCity.getId())).find(County.class);

        if(countyList.size()>0){
            //成功从数据库表中获取数据
            dataList.clear();//清除原来的所有数据
            countyList.forEach(item->{
                dataList.add(item.getCountyName());
            });
            adapter.notifyDataSetChanged();
            binding.listView.setSelection(0);
            currentLevel=LEVEL_COUNTY;
        }else{
            //数据库表是空表，发网络请求，获取数据，填充数据
            String url=PROVINCE_URL+"/"+selectedProvince.getProvinceCode()+"/"+selectedCity.getCityCode();
            queryFromServer(url, COUNTY);
        }
    }

    private void queryCities() {
        binding.titleText.setText(selectedProvince.getProvinceName());
        binding.backButton.setVisibility(View.VISIBLE);//有返回按钮，可以返回到省一级

        //访问数据库表
        cityList = LitePal.where("provinceId=?",
                String.valueOf(selectedProvince.getId())).find(City.class);

        if(cityList.size()>0){
            //成功从数据库表中获取数据
            dataList.clear();//清除原来的所有数据
            cityList.forEach(item->{
                dataList.add(item.getCityName());
            });
            adapter.notifyDataSetChanged();
            binding.listView.setSelection(0);
            currentLevel=LEVEL_CITY;
        }else{
            //数据库表是空表，发网络请求，获取数据，填充数据
            String url=PROVINCE_URL+"/"+selectedProvince.getProvinceCode();
            queryFromServer(url, CITY);
        }
    }

    private void queryProvinces() {
        //尝试从本地SQLite3数据库中访 问省份表，尝试获取省份列表数据
        //如果说：成功了，说明你不是第一次访问，上一次已经把数据存储起来了
        //要做的：遍历省份列表数据---》省份名称填写到dataList中去（填写之前，先清空dataList)
        //如果没拿到，发起网络请求，拿数据存入库中，最后再去queryProvinces()
        binding.titleText.setText("中国(China)");
        binding.backButton.setVisibility(View.GONE);//没有返回按钮

        //访问数据库表
        provinceList = LitePal.findAll(Province.class);//ctrl+alt+v
        if(provinceList.size()>0){
            //成功从数据库表中获取数据
            dataList.clear();//清除原来的所有数据
            provinceList.forEach(item->{
                dataList.add(item.getProvinceName());
            });
            adapter.notifyDataSetChanged();
            binding.listView.setSelection(0);
            currentLevel=LEVEL_PROVINCE;
        }else{
            //数据库表是空表，发网络请求，获取数据，填充数据
           queryFromServer(PROVINCE_URL, PROVINCE);
        }

    }

    /**
     *
     * @param url 网络访问请求地址
     * @param type  类型  province 访问省份数据  city  访问市数据  county  访问县数据
     */
    private void queryFromServer(String url, String type) {
        Log.d("test", url);
        showProgressDialog();//显示加载进度对话框
        HttpUtil.sendOkHttpRequest(url, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                getActivity().runOnUiThread(()->{
                    Toast.makeText(getContext(), "访问网络失败！", Toast.LENGTH_SHORT).show();
                    closeProgressDialog();
                });
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
             //解析数据  放在子线程中
                String strJson = response.body().string();//ctrl+alt+v
                Log.d("test", "onResponse: "+strJson);
                boolean result=false;
                if(PROVINCE.equals(type)){
                    result = Utility.handleProvinceResponse(strJson);//写入数据库表
                }else if(CITY.equals(type)){
                    result =Utility.handleCityResponse(strJson,selectedProvince.getId());
                }else if(COUNTY.equals(type)){
                    result =Utility.handleCountyResponse(strJson,selectedCity.getId());
                }
                if(result){
                    if(PROVINCE.equals(type)){
                        getActivity().runOnUiThread(()->{
                            queryProvinces();
                        });
                    }else if(CITY.equals(type)){
                        getActivity().runOnUiThread(()->{
                            queryCities();
                        });
                    }else if(COUNTY.equals(type)){
                        getActivity().runOnUiThread(()->{
                            queryCounties();
                        });
                    }
                    closeProgressDialog();
                }else{
                    getActivity().runOnUiThread(()->{
                        Toast.makeText(getContext(),
                                "数据解析失败", Toast.LENGTH_SHORT).show();
                        closeProgressDialog();
                    });
                }
//显示数据  (再次调用queryProvinces() )

            }
        });
    }

    private void closeProgressDialog() {
        if(progressDialog!=null){
            progressDialog.dismiss();
        }

    }

    private void showProgressDialog() {
        if(progressDialog==null){
            //创建对话框
            progressDialog=new ProgressDialog(getContext());
            progressDialog.setMessage("正在访问网络，请稍候！");
            progressDialog.setCancelable(false);
        }
        progressDialog.show();
    }
}
